<?php

namespace App\Http\Controllers;

use DB;
use App\Models\User;
use App\Models\Share;
use App\Models\System;
use App\Models\Circle;
use App\Models\UserBill;
use App\Models\MealCate;
use App\Models\MealCard;
use App\Models\MealShop;
use App\Models\MealOrder;
use App\Models\UserIncome;
use App\Models\MealCompany;
use App\Models\HelpAddress;
use Illuminate\Http\Request;
use App\Models\MealUserCard;
use App\Models\MealHelpOrder;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;

class MealOrderController extends Controller
{

    //
    public function orderListAll(Request $request)
    {
        $order = new MealOrder;
    	$orders = $order->list(false,15,$request->input('keyword',false));
    	$orderstatus_de = ['-2'=>"已撤销",'-1'=>'加价未支付','1'=>'已取餐','0'=>'未取餐','2'=>'已超时','3'=>"取消订单"];
        $qc_de = [0=>'到店',1=>'打包带走',2=>'朋友帮带',3=>"乐享专送"];
    	return view('shop.orders',['orders'=>$orders,'orderstatus_de'=>$orderstatus_de,'qc_de'=>$qc_de]);
    }

    /**
     * 取消用户订单
     */
    public function orderClean(Request $request)
    {
    	$orderid = $request->input('order_id');
        $cardInfo = MealOrder::leftJoin('lexiang_meal_user_card','lexiang_meal_order.cards_id','=','lexiang_meal_user_card.card_identi')
        ->leftJoin('lexiang_meal_card','card_frequency','lexiang_meal_user_card.cards_id','=','lexiang_meal_card.card_id')
        ->where('lexiang_meal_order.order_id',$orderid)
        ->select('lexiang_meal_card.start_time'
            ,'lexiang_meal_card.stop_time'
            ,'lexiang_meal_user_card.card_identi'
            ,'lexiang_meal_order.order_id'
            ,'lexiang_meal_order.shops_id'
            ,'lexiang_meal_order.users_id'
            ,'lexiang_meal_order.meal_order_price'
            ,'lexiang_meal_order.order_status'
            ,'lexiang_meal_order.markup'
            ,'lexiang_meal_order.pay_price'
            ,'lexiang_meal_order.order_number'
        )
        ->first();
        $nowtime = time();
        // $starttime = strtotime($cardInfo['start_time']);
        // $stoptime = strtotime($cardInfo['stop_time']);
        // if($starttime < $nowtime && $stoptime > $nowtime){
        //     return response()->json(['success'=>false,'code'=>'1','message'=>$cardInfo['start_time'].' - '.$cardInfo['stop_time'].'不可执行该操作！']);
        // }
        // 事务处理
        DB::beginTransaction();
        // 下单用户卡ID
        $usercard = MealUserCard::find($cardInfo['card_identi']);
        // 商户信息
        $shop = MealShop::find($cardInfo['shops_id']);
        // 商户账号
        $user = User::find($shop->users_id);
        // 订单信息
        // $orderInfo = MealOrder::where('order_id',$orderid)->first();
        if($user->account < $cardInfo->meal_order_price){
            return response()->json(['success'=>false,'code'=>'004','message'=>'商家余额不足，请联系商家处理']);
        }
        $user->account = ($user->account-$cardInfo->meal_order_price);
        $usercard->card_num = $usercard->card_num+1;
        $usercard->card_already_num = $usercard->card_already_num-1;
        $usercard->update_time = null;
        // $orderInfo->order_status = 3;
        $cardInfo->order_status = -2;
        if($cardInfo->markup == 1 && $cardInfo->pay_price > 0){
            // 执行退款
            require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
            $wx = new \Wxpayandroid;
            $tui = $wx->refund($cardInfo->pay_price,$cardInfo->order_number);
            if(!$tui['success']){
                DB::rollback();
                return response()->json(['success'=>false,'code'=>'003','message'=>'退款失败，请稍后再试','data'=>$tui['data']]);
            }
        }
        if(!$cardInfo->save()){
            DB::rollback();
            return response()->json(['success'=>false,'code'=>'003','message'=>'保存出错，请稍后再试']);
        }
        if(!$usercard->save()){
            DB::rollback();
            return response()->json(['success'=>false,'code'=>'003','message'=>'保存出错，请稍后再试']);
        }
        if(!$user->save()){
            DB::rollback();
            return response()->json(['success'=>false,'code'=>'003','message'=>'保存出错，请稍后再试']);
        }
        DB::commit();
        return response()->json(['success'=>true,'code'=>'000','message'=>'操作成功，饭卡次数恢复给用户']);
    }

    /**
     * 下单信息检测
     */
    public function orderbuyInfo(Request $request)
    {
        $nowTime = time();
        $userid = $request->input('user_id');
        $shopid = $request->input('shop_id');
        $card = new MealUserCard;
        $shop = new MealShop;
        $user = new User;
        $mycard = $card
        ->where([
            ['users_id','=',$userid],
            ['card_invalid','=',1],
            ['card_num','>',0],
        ])
        ->get();
        $usercircleid = $user->where('user_id',$userid)->value('circle_range_id');
        $pscount = $user->where('circle_id',$usercircleid)->count();
        $shopciecleid = $shop->where('shop_id',$shopid)->value('circle_id');
        if($usercircleid == $shopciecleid && !empty($usercircleid) && !empty($shopciecleid)){
            $peisong = true;
        }else{
            $peisong = false;
        }
        $ka = false;
        if($mycard->count() > 0){
            $ka = true;
        }
        if(!empty($mycard->card_endtime)){
            if(strtotime($mycard->card_endtime.' 23:59:59') < $nowTime){
                $ka = false;
            }
        }
        $circleDelivery = true;
        if($pscount <= 0){
            $circleDelivery = false;
            $peisong = false;
        }
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'获取完成',
            'data'=>[
                'mycard'=>$mycard,
                'delivery'=>$peisong,
                'incard'=>$ka,
                'circle_delivery'=>$circleDelivery,
            ]
        ]);
    }

    /**
     * 直接下单
     */
    public function placeOrder(Request $request)
    {
        $shops_id = $request->input('shops_id');
        $users_id = $request->input('users_id');
        $cates_id = $request->input('cates_id');
        $order_type = $request->input('order_type');
        $order_remarks = $request->input('order_remarks');
        $card_identi = $request->input('card_identi');
        $cate_num = $request->input('cate_num',1);
        $userCard = new MealUserCard;
        return response()->json($userCard->useCard($card_identi,$cates_id,$users_id,$shops_id,$order_remarks,$order_type,0,$cate_num));
    }

    /**
     * 今日订单
     */
    public function dayorders(Request $request)
    {
        $order = new MealOrder;
        $orders = $order->list(false,15,$request->input('keyword',false),'day');
        $orderstatus_de = ['-2'=>'取消订单','-1'=>'加价未支付','1'=>'已取餐','0'=>'未取餐','2'=>'已超时','3'=>"取消订单"];
        $qc_de = [0=>'到店',1=>'打包带走',2=>'朋友帮带',3=>"乐享专送"];
        return view('shop.orders',['orders'=>$orders,'orderstatus_de'=>$orderstatus_de,'qc_de'=>$qc_de]);
    }

    /**
     * 搜索用户
     */
    public function findUser(Request $request)
    {
        $tel = $request->input('tel');
        $user = User::where([['tel','=',$tel],['user_ttp','=',1]])->where('tel','<>',null)->select('tel','nicename','avatar','user_id')->first();
        if($user){
            return response()->json([
                'success'=>true,
                'code'=>"000",
                'message'=>"搜索成功",
                "data"=>$user
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>"004",
                'message'=>"没有这个用户",
                "data"=>[]
            ]);
        }
    }

    /**
     * 用户订单列表
     */
    public function orderLists(Request $request)
    {
        $orders = MealOrder::where('lexiang_meal_order.users_id',$request->input('user_id'))
        ->where('lexiang_meal_order.order_status','>',-1)
        ->leftJoin('lexiang_meal_shop','lexiang_meal_shop.shop_id','=','lexiang_meal_order.shops_id')
        ->leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_meal_order.users_id')
        ->leftJoin('lexiang_meal_cate','lexiang_meal_cate.cate_id','=','lexiang_meal_order.cates_id')
        ->selectRaw('lexiang_meal_shop.shop_name,lexiang_meal_order.*,lexiang_user.nicename,lexiang_meal_cate.cate_name,lexiang_meal_shop.shop_name,lexiang_meal_shop.shop_address,lexiang_meal_cate.cate_imgs,lexiang_meal_cate.cate_desc,null as created_at,null as cate_img_qu,null as help_tel,lexiang_meal_shop.shop_tel,null as scancode')
        ->orderBy('lexiang_meal_order.insert_time','desc')
        ->paginate(10);

        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'data'=>$orders
        ]);
    } 

    /**
     * 申请授权
     */
    public function applybangd(Request $request)
    {
        $touserid = $request->input('touser_id');
        $userid = $request->input('user_id');
        $isamount = $request->input('is_amount',0);
        
        $orderid = $request->input('order_id');
        $openid = $request->input('openid');
        $action = $request->input('action',1);
        $card = new MealUserCard;
        // $cards = $card->where(['users_id'=>$touserid])->count();
        // if($cards <= 0){
        //     return response()->json([
        //         'success'=>false,
        //         'code'=>'004',
        //         'message'=>'对方没有饭卡无法授权'
        //     ]);
        // }
        $order = new MealOrder;
        $orderInfo = $order->where([
            ['order_id','=',$request->input('order_id')]
        ])->orWhere('order_number',$request->input('order_id'))->first();
        $shopInfo = MealShop::where('shop_id',$orderInfo->shops_id)->first();
        $touserInfo = User::where('user_id',$touserid)->first();
        /*if($touserInfo->circle_id == $shopInfo->circle_id && !empty($touserInfo->circle_id)){
            // 乐享专送
            $amount = 3.00;
        }else{
            // 朋友帮带
            $amount = 1.00;
        }*/
        // 朋友帮带
        $amount = 1.00;
        if($action==0){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'获取成功',
                'amount'=>$amount
            ]);
        }
        if(!$request->input('name',false)){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'请填写收货人姓名'
            ]);
        }
        if(!$request->input('tel',false)){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'请填写联系电话'
            ]);
        }
        if(!$request->input('address',false)){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'请填写收货地址'
            ]);
        }
        if($touserid==$userid){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'不能给自己下单！'
            ]);
        }
        if($isamount){
            $bill = new UserBill;
            $res = $bill->insertBill([
                'payee_id'=>0,
                'price'=>$amount,
                'bewrite'=>'帮带支出',
                'effect'=>1,
            ],$userid);
            if(!$res['success']){
                return response()->json($res);
            }
            // 推送
            $order->sendWebSocket($orderInfo->order_id,$orderInfo->shops_id);
        }
        $help = new MealHelpOrder;
        $data = [
            'meal_order_id'=>$orderid,
            'users_id'=>$userid,
            'amount'=>$amount,
            'to_users_id'=>$touserid,
            'is_amount'=>$isamount,
        ];
        $address = new HelpAddress;
        $addres = $address->saveadd($request->all());
        if(!$addres['success']){
            return response()->json($res);
        }

        $res = $help->add($data);
        if(!$res['success'] || $isamount){
            return response()->json($res);
        }
        
        require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
        $notifyUrl = "http://console.jiashilexiang.cn/api/meal/apply/notify/";
        $wx = new \Wxpayandroid;
        return response()->json($wx->WeixinpayXcx($amount,$res['data']['order_number'],"嘉时乐享 - 帮带下单",$openid,$notifyUrl));
    }

    public function applybangdLezs(Request $request)
    {
        $help = new MealHelpOrder;
        $userid = $request->input('user_id');
        $shopid = $request->input('shop_id');
        $orderid = $request->input('order_id');
        if(!$request->input('name',false)){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'请填写收货人姓名'
            ]);
        }
        if(!$request->input('tel',false)){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'请填写联系电话'
            ]);
        }
        if(!$request->input('address',false)){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'请填写收货地址'
            ]);
        }
        $selfInfo = User::where('user_id',$userid)->first();
        if($help->where([
            ['meal_order_id','=',$orderid],
            ['status','=',1],
        ])->exists()){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'您的配送订单已送达配送员手中，请勿重复下单'
            ]);
        }
        $order = new MealOrder;
        $orderInfo = $order->where([
            ['order_id','=',$orderid]
        ])->orWhere('order_number',$orderid)->first();
        $shopInfo = MealShop::where('shop_id',$orderInfo->shops_id)->first();
        $nowtime = time();
        /*if(strtotime(date('Y-m-d 13:30:00')) < $nowtime){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'配送员累坏了，在休息呢。辛苦您自取一下吧~'
            ]);
        }*/

        if($selfInfo->circle_range_id != $shopInfo->circle_id){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'您和饭店不在同一商圈，不能配送'
            ]);
        }

        $touserid = $help->getPeisong($selfInfo->circle_range_id);
        if(!$touserid['success']){
            return response()->json($touserid);
        }
        $touserid = $touserid['data'];
        $isamount = $request->input('is_amount',0);
        if($touserid==$userid){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'不能给自己下单！'
            ]);
        }

        $orderid = $request->input('order_id');
        $openid = $request->input('openid');
        $action = $request->input('action',1);
        $card = new MealUserCard;
        
        $touserInfo = User::where('user_id',$touserid)->first();
        if($touserInfo->circle_id == $shopInfo->circle_id && !empty($touserInfo->circle_id)){
            // 乐享专送
            $amount = 3.00;
        }else{
            // 朋友帮带
            $amount = 1.00;
        }
        $cardinfo = MealUserCard::leftJoin('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_meal_user_card.cards_id')
        ->where('lexiang_meal_user_card.card_identi',$orderInfo->cards_id)
        ->select('lexiang_meal_card.delivery_free','lexiang_meal_card.card_id')
        ->first();
        $mianpei = false;
        if($cardinfo->delivery_free == 1){ // 免费专送
            $amount = 0.00;
            $isamount = false;
            $mianpei = true;
        }
        if($action==0){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'获取成功',
                'amount'=>$amount
            ]);
        }
        if($isamount){
            $bill = new UserBill;
            $res = $bill->insertBill([
                'payee_id'=>0,
                'price'=>$amount,
                'bewrite'=>'帮带支出',
                'effect'=>1,
            ],$userid);
            if(!$res['success']){
                return response()->json($res);
            }
            // 推送
            $order->sendWebSocket($orderInfo->order_id,$orderInfo->shops_id);
        }
        if($cardinfo->delivery_free == 1){ // 免费专送
            $isamount = 1;
        }
        $data = [
            'meal_order_id'=>$orderid,
            'users_id'=>$userid,
            'amount'=>$amount,
            'to_users_id'=>$touserid,
            'is_amount'=>$isamount,
            'free_peisong'=>$mianpei
        ];
        $address = new HelpAddress;
        $addres = $address->saveadd($request->all());
        if(!$addres['success']){
            return response()->json($res);
        }
        $res = $help->add($data);
        if(!$res['success'] || $isamount){
            return response()->json($res);
        }
        require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
        $notifyUrl = "http://console.jiashilexiang.cn/api/meal/apply/notify/";
        $wx = new \Wxpayandroid;
        return response()->json($wx->WeixinpayXcx($amount,$res['data']['order_number'],"嘉时乐享 - 帮带下单",$openid,$notifyUrl));
    }

    /**
     * 加价
     */
    public function markup(Request $request)
    {
        // 
        $shops_id = $request->input('shops_id');
        $users_id = $request->input('users_id');
        $cates_id = $request->input('cates_id');
        $order_type = $request->input('order_type');
        $order_remarks = $request->input('order_remarks');
        $card_identi = $request->input('card_identi');
        $cate_num = $request->input('cate_num',1);
        $userCard = new MealUserCard;
        $userCardInfo = MealUserCard::where('card_identi',$card_identi)->first();
        $cardInfo = MealCard::where('card_id',$userCardInfo->cards_id)->first();
        $cateInfo = MealCate::where('cate_id',$cates_id)->first();
        $userInfo = User::where('user_id',$users_id)->first();
        if(!$userInfo){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'不存在的用户'
            ]);
        }
        if($cateInfo->cate_price > $cardInfo->meal_max_price){
            $jiaprice = $cateInfo->cate_price - $cardInfo->meal_max_price;
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'无需加价'
            ]);
        }
        $jiaprice = round($jiaprice*$cate_num,2);
        $orderes = $userCard->useCard($card_identi,$cates_id,$users_id,$shops_id,$order_remarks,$order_type,0,$cate_num,1,0,false,$jiaprice);
        if(!$orderes['success']){
            return response()->json($orderes);
        }
        require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
        $notifyUrl = "http://console.jiashilexiang.cn/api/meal/markup/notify/";
        $wx = new \Wxpayandroid;
        return response()->json($wx->WeixinpayXcx($jiaprice,$orderes['data']['order_number'],"嘉时乐享 - 加价下单",$userInfo->small_program_code,$notifyUrl));
    }

    /**
     * 购物车下单
     */
    public function cartOrder(Request $request)
    {
        // 
        $shops_id = $request->input('shops_id');
        $users_id = $request->input('users_id');
        $cates_id = explode(',',$request->input('cates_id'));
        $order_type = $request->input('order_type');
        $order_remarks = $request->input('order_remarks');
        $card_identi = $request->input('card_identi');
        $cate_num = $request->input('cate_num',1);
        $carts = json_decode($request->input('carts'),true); 
        
        if(empty($carts)){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'购物车是空的'
            ]);
        }
        $userCard = new MealUserCard;
        $userCardInfo = MealUserCard::where('card_identi',$card_identi)->first();
        $cardInfo = MealCard::where('card_id',$userCardInfo->cards_id)->first();
        $cateInfo = MealCate::whereIn('cate_id',$cates_id)->get();
        $userInfo = User::where('user_id',$users_id)->first();
        if(!$userInfo){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'不存在的用户'
            ]);
        }
        $totalprice = 0;
        foreach ($cateInfo as $key => $value) {
            $num = 1;
            foreach ($carts as $v) {
                if($v['cate_id'] == $value->cate_id){
                    $num = $v['select_num'];
                }
            }
            $value->cate_price = $num*$value->cate_price;
            $totalprice = $totalprice+$value->cate_price;
        }
        if($totalprice > $cardInfo->meal_max_price){
            $jiaprice = $totalprice - $cardInfo->meal_max_price;
        }else{
            return response()->json($userCard->useCard($card_identi,$cates_id,$users_id,$shops_id,$order_remarks,$order_type,0,$cate_num,3,0,$carts));
        }
        $jiaprice = round($jiaprice,2);
        $orderes = $userCard->useCard($card_identi,$cates_id,$users_id,$shops_id,$order_remarks,$order_type,0,$cate_num,2,0,$carts,$jiaprice);
        if(!$orderes['success']){
            return response()->json($orderes);
        }
        require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
        $notifyUrl = "http://console.jiashilexiang.cn/api/meal/markup/notify/";
        $wx = new \Wxpayandroid;
        return response()->json($wx->WeixinpayXcx($jiaprice,$orderes['data']['order_number'],"嘉时乐享 - 加价下单",$userInfo->small_program_code,$notifyUrl));
    }

    /**
     * 回调
     */
    public function notifyUrl(Request $request)
    {
        $nowtime = time();
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        // file_put_contents(base_path('storage/logs/').'wxpay.log', $xml."\n---------\n", FILE_APPEND);
        // 将服务器返回的XML数据转化为数组
        // 将XML转为array
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents(base_path('storage/logs/').'wxpay.log', json_encode($data)."\n---------\n", FILE_APPEND);
        $order = new MealHelpOrder;
        $mealorder = new MealOrder;
        $orderInfo = $order->where([
            ['order_number','=',$data['out_trade_no']],
        ])->first();
        if($orderInfo->status == 1){
            echo 'success';die;
        }
        $mealInfo = $mealorder->where('order_id',$orderInfo->meal_order_id)->first();
        if($data['result_code']!='SUCCESS'){
            echo 'fail';die;
        }
        
        $mealInfo->help_state = 1;
        $orderInfo->status = 1;
        $orderInfo->wx_order_number = $data['transaction_id'];
        $mealInfo->save();
        $sendMsg = [
            'cates_id'=>$mealInfo->cates_id,
            'shops_id'=>$mealInfo->shops_id,
            'users_id'=>$mealInfo->help_user_id,
            'order_sernum'=>$mealInfo->order_sernum,
        ];
        // 微信推送
        $order->wechatRemind($sendMsg);
        if($orderInfo->save()){
            // 推送
            $mealorder->sendWebSocket($mealInfo->order_id,$mealInfo->shops_id);
            echo 'success';die;
        }else{
            echo 'fail';die;
        }
    }

    /**
     * 加价回调
     */
    public function MarkupNotifyUrl(Request $request)
    {
        $nowtime = time();
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        file_put_contents(base_path('storage/logs/').'wxpay.log', $xml."\n-----new----\n", FILE_APPEND);
        // 将服务器返回的XML数据转化为数组
        // 将XML转为array
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        // file_put_contents(base_path('storage/logs/').'wxpay.log', json_encode($data)."\n---------\n", FILE_APPEND);
        // $order = new MealHelpOrder;
        $mealorder = new MealOrder;
        $usercard = new MealUserCard;
        $orderInfo = $mealorder->where([
            ['order_number','=',$data['out_trade_no']],
        ])->first();
        $cardInfo = $usercard->join('lexiang_meal_card','lexiang_meal_card.card_id','=','lexiang_meal_user_card.cards_id')
        ->where([
            ['lexiang_meal_user_card.card_identi','=',$orderInfo->cards_id]
        ])
        ->select('lexiang_meal_user_card.*','lexiang_meal_card.card_frequency')
        ->first();
        if($orderInfo->order_status == 0){
            echo 'success';die;
        }
        if($data['result_code']!='SUCCESS'){
            echo 'fail';die;
        }
        $shop = new MealShop;
        $shopinfo_re = $shop->where('shop_id',$orderInfo->shops_id)->first();
        $shopinfo = User::where('user_id',$shopinfo_re->users_id)->first();

        $shopinfo->account = round($shopinfo->account+$orderInfo->meal_order_price,2);
        $orderInfo->order_status = 0;
        $orderInfo->wx_order_number = $data['transaction_id'];
        $orderInfo->pay_at = $nowtime;
        if($cardInfo->card_already_num == 0 && ($cardInfo->card_type == 0 || $cardInfo->card_type == 2)){
            $time30Day=strtotime(date('Y-m-d'))+($cardInfo->card_frequency*24*3600);
            $cardInfo->card_endtime = date('Y-m-d',$time30Day);
        }
        $cardInfo->card_already_num = $cardInfo->card_already_num + $orderInfo->cate_num;
        $cardInfo->card_num = $cardInfo->card_num - $orderInfo->cate_num;
        if($cardInfo->card_num <= 0){
            $cardInfo->card_invalid = 0;
        }
        $cardInfo->update_time = $nowtime;
        $shopinfo->save();
        $cardInfo->save();
        if($orderInfo->save()){
            if($orderInfo->order_type != 2 && $orderInfo->order_type != 1){
                $this->sendWebSocket($orderInfo->order_id,$orderInfo->shops_id);
            }
            echo 'success';die;
        }else{
            echo 'fail';die;
        }
    }

    /**
     * 查询信息
     */
    public function getNews(Request $request)
    {
        $userid = $request->input('user_id');
        $order = new MealHelpOrder;
        $s = $order
        ->join('lexiang_meal_order as lmo','lmo.order_id','=','lexiang_meal_help_order.meal_order_id')
        ->join('lexiang_user as lu','lu.user_id','=','lexiang_meal_help_order.users_id')
        ->join('lexiang_meal_cate as lmc','lmc.cate_id','=','lmo.cates_id')
        ->join('lexiang_meal_shop as lms','lmc.shops_id','=','lms.shop_id')
        ->join('lexiang_help_address as lha','lha.user_id','=','lu.user_id')
        ->where([
            ['lexiang_meal_help_order.to_users_id','=',$userid],
            ['lexiang_meal_help_order.entrust','<>',-1],
            ['lexiang_meal_help_order.status','=',1],
        ])
        // ->select('lexiang_meal_help_order.*','lu.nicename','lmc.cate_name','lms.shop_name','lmo.order_sernum')
        ->select('lu.nicename','lu.tel','lexiang_meal_help_order.*','lmo.order_number as or_order_number','lmc.cate_name','lmc.cate_imgs','lms.shop_name','lms.shop_address','lmo.order_remarks','lmc.cate_desc','lha.name','lha.tel as help_tel','lha.address','lmo.order_sernum','lmo.cart_cates')
        ->orderBy('lexiang_meal_help_order.created_at','desc')
        ->paginate(10);

        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询成功',
            'data'=>$s
        ]);
    }

    /**
     * 查询是否有新订单
     */
    public function newOrder(Request $request)
    {
        $userid = $request->input('user_id');
        $order = new MealOrder;

        $s = $order->where([
            ['help_user_id','=',$userid],
            ['help_state','=',1],
        ])->count();

        if($s > 0){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'Hi~有朋友委托您帮带餐品', 
                'data'=>$s
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'没有新订单'
            ]);
        }
    }

    /**
     * 接受或拒绝委托
     */
    public function entrustAction(Request $request)
    {
        $t = $request->input('action','jujue');
        $userid = $request->input('user_id');
        $orderid = $request->input('order_id');
        $helpInfo = MealHelpOrder::where([
            ['id','=',$orderid],
            ['status','=',1],
        ])->first();
        $orderInfo = MealOrder::where('order_id',$helpInfo->meal_order_id)->first();
        
        if($helpInfo->entrust == 2){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'订单已经被处理过了'
            ]);
        }

        if($orderInfo->help_user_id != $userid){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'您不是指定的授权用户'
            ]);
        }
        if($t=='jieshou'){
            $helpInfo->entrust = 1;
            $orderInfo->help_state = 2;
            if(!$orderInfo->save()){
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>'操作出错，请稍后再试！'
                ]);
            }
            if(!$helpInfo->save()){
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>'操作出错，请稍后再试！'
                ]);
            }
            
            $income = new UserIncome;
            // $amount = 0;
            if($helpInfo->amount > 0.01){
                $shopInfo = MealShop::where('shop_id',$orderInfo->shops_id)->first();
                $touserInfo = User::where('user_id',$userid)->first();
                if($touserInfo->circle_id == $shopInfo->circle_id){
                    $amount = 2.00;
                }else{
                    $amount = $helpInfo->amount / 2;
                }
            }else{
                $amount = $helpInfo->amount;
            }
            // $amount = 1.00;
            $data = [
                'income_value'=>$amount,
                'users_id'=>$userid,
                'source'=>2,
                'bewrite'=>"帮带收入",
            ];
            $r = $income->add($data);
            if(!$r['success']){
                return response()->json($r);
            }

            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'已接受，请尽快取餐',
                'amount'=>$amount
            ]);
            
        }else if($t=='jujue'){
            if($helpInfo->is_amount==1){
                /*$income = new UserIncome;
                $amount = 1;
                $data = [
                    'income_value'=>$amount,
                    'users_id'=>$orderInfo->users_id,
                    'source'=>3,
                    'bewrite'=>"帮带退款",
                ];
                $r = $income->add($data);
                if(!$r['success']){
                    return response()->json($r);
                }*/
            }else{
                // 执行退款
                require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
                $wx = new \Wxpayandroid;
                $tui = $wx->refund($helpInfo->amount,$helpInfo->order_number);
                if(!$tui['success']){
                    return response()->json($tui);
                }
            }
           
            $helpInfo->entrust = -1;
            $orderInfo->help_state = -1;
            $orderInfo->help_user_id = 0;
            if(!$orderInfo->save()){
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>'操作出错，请稍后再试！'
                ]);
            }
            if(!$helpInfo->save()){
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>'操作出错，请稍后再试！'
                ]);
            }
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'已拒绝'
            ]);
        }else if($t=='songda'){
            $helpInfo->entrust = 2;
            if($helpInfo->save()){
                return response()->json([
                    'success'=>true,
                    'code'=>'000',
                    'message'=>'已送达'
                ]);
            }else{
                return response()->json([
                    'success'=>false,
                    'code'=>'004',
                    'message'=>'修改出错，请稍后再试'
                ]);
            }
        }
    }

    /**
     * 帮带记录
     */
    public function bangdailog(Request $request)
    {
        $userid = $request->input('user_id');
        $help = new MealHelpOrder;

        $userids = $help->where('users_id',$userid)->pluck('to_users_id');
        $users = User::whereIn('user_id',$userids)
        ->select('tel','nicename as value','avatar','user_id as name')
        ->get();

        if($users){
            return response()->json([
                'success'=>true,
                'code'=>"000",
                'message'=>"搜索成功",
                "data"=>$users
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>"004",
                'message'=>"没有这个用户",
                "data"=>[]
            ]);
        }
    }

    /**
     * 获取余额
     */
    public function getAmount(Request $request)
    {
        $user = new User;
        $info = $user->where('user_id',$request->input('user_id'))->first();
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'account'=>$info->account
        ]);
    }

    /**
     * 详情
     */
    public function detailEntrust(Request $request)
    {
        $orderid = $request->input('order_id');
        $info = MealHelpOrder::join('lexiang_user as lu','lu.user_id','=','lexiang_meal_help_order.users_id')
        ->join('lexiang_meal_order as lmo','lmo.order_id','=','lexiang_meal_help_order.meal_order_id')
        ->join('lexiang_meal_cate as lmc','lmc.cate_id','=','lmo.cates_id')
        ->join('lexiang_meal_shop as lms','lms.shop_id','=','lmo.shops_id')
        ->join('lexiang_help_address as lha','lha.user_id','=','lu.user_id')
        ->where('lexiang_meal_help_order.id',$orderid)
        ->select('lu.nicename','lu.tel','lexiang_meal_help_order.*','lmo.order_number as or_order_number','lmc.cate_name','lmc.cate_imgs','lms.shop_name','lms.shop_address','lmo.order_remarks','lmc.cate_desc','lha.name','lha.tel as help_tel','lha.address','lms.shop_tel')
        ->first();
        if($info){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'查询完成',
                'data'=>$info
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>'没查询到'
            ]);
        }
    }


    /**
     * 所属商圈下的配送员
     */
    public function circleDelivery(Request $request)
    {
        $user = new User;
        $shop = new MealShop;
        $shopId = $request->input('shop_id',false);
        $userId = $request->input('user_id',false);
        if(!$shopId){
            $orderId = $request->input('order_id');
            $orderinfo = MealOrder::where('order_id',$orderId)->orWhere('order_number',$orderId)->first();
            $shopId = $orderinfo->shops_id;
            $userId = $orderinfo->users_id;
        }
        $shopinfo = $shop->where('shop_id',$shopId)->first();
        if(!$user->where('circle_range_id',$shopinfo->circle_id)->where('user_id',$userId)->first()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'查询完成',
                'data'=>[]
            ]);
        }
        if($shopinfo){
            $users = $user->where('circle_id',$shopinfo->circle_id)->select('tel','nicename as value','avatar','user_id as name')->get();
        }else{
            $users = [];
        }
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'data'=>$users
        ]);
    }

    /**
     * 获取帮带地址
     */
    public function getAddress(Request $request)
    {
        $address = new HelpAddress;
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'data'=>$address->where('user_id',$request->input('user_id'))->first()
        ]);
    }

    /**
     * 红包列表
     */
    public function redpackList(Request $request)
    {
        $share = new Share;
        $status = $request->input('status',false);
        $w[] = ['toorme','=',0];
        if($status!==false){
            $w[] = ['status','=',$status];
        }
        $sharelist = $share->where($w)
        ->selectRaw('*,null as share_user_name,null as user_name,null as card_name,null as get_if')
        ->orderBy('created_at','desc')
        ->paginate(15);
        return view('user.redpack',['sharelist'=>$sharelist,'request'=>$request]);
    }

    /**
     * 索取所在商圈
     */
    public function getCircleName(Request $request)
    {
        require(base_path('app/Packages/').'checkzbCode.php');
        $lat = $request->input('lat',0);
        $lng = $request->input('lng',0);
        $city = $request->input('city',false);
        $userid = $request->input('user_id');
        /*if($city){
            $w[] = ["city",'=',$city];
        }*/
        $circle = new Circle;
        $circleObj = $circle
        ->select(DB::raw('*,(POWER(MOD(ABS(lng - '.$lng.'),360),2) + POWER(ABS(lat - '.$lat.'),2)) AS distance,'.$lng.' as lng2,'.$lat.' as lat2,null as coupon_distance'))
        ->when($city,function($q)use($city){
           return $q->where("city",$city);
        })
        ->orderBy('distance','asc');
        $data = $circleObj->first();
        $map = json_decode($data->position,true);
        \validationMap::setCoordArray($map);
        $xy = ['lat'=>$lat,'lng'=>$lng];// 不在内
        // if($data->coupon_distance > $data->circle_range){
        if(\validationMap::isCityCenter($xy)){
            User::where('user_id',$userid)->update(['circle_range_id'=>$data->circle_id,'last_position_lat'=>$lat,'last_position_lng'=>$lng]);
        }else{
            $alldata = $circleObj->take(3)->get();
            $inl = false;
            foreach ($alldata as $value) {
                $map = json_decode($value->position,true);
                \validationMap::setCoordArray($map);
                if(\validationMap::isCityCenter($xy)){
                    $inl = true;
                    User::where('user_id',$userid)->update(['circle_range_id'=>$value->circle_id,'last_position_lat'=>$lat,'last_position_lng'=>$lng]);
                    $data = $value;
                    break;
                }
            }
            if(!$inl){
                User::where('user_id',$userid)->update(['circle_range_id'=>0,'last_position_lat'=>$lat,'last_position_lng'=>$lng]); 
                return response()->json([
                    'success'=>false,
                    'code'=>"000",
                    'message'=>'当前位置不在可配送范围',
                    'data'=>$data,
                ]);
            }
        }
        return response()->json([
            'success'=>true,
            'code'=>"000",
            'message'=>'查询成功',
            'data'=>$data,
        ]);
    }

    /**
     * 扫码取餐
     */
    public function scanQrcode(Request $request)
    {
        $userid = $request->input('user_id');
        $shopid = $request->input('shop_id');
        $orders = MealOrder::where([
            ['lexiang_meal_order.shops_id','=',$shopid],
            ['lexiang_meal_order.users_id','=',$userid],
            ['lexiang_meal_order.order_status','=',0],
        ])->orWhere([
            ['lexiang_meal_order.shops_id','=',$shopid],
            ['lexiang_meal_order.help_user_id','=',$userid],
            ['lexiang_meal_order.order_status','=',0],
        ])
        ->leftJoin('lexiang_meal_shop','lexiang_meal_shop.shop_id','=','lexiang_meal_order.shops_id')
        ->leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_meal_order.users_id')
        ->leftJoin('lexiang_meal_cate','lexiang_meal_cate.cate_id','=','lexiang_meal_order.cates_id')
        ->selectRaw('lexiang_meal_shop.shop_name,lexiang_meal_order.*,lexiang_user.nicename,lexiang_meal_cate.cate_name,lexiang_meal_shop.shop_name,lexiang_meal_shop.shop_address,lexiang_meal_cate.cate_imgs,lexiang_meal_cate.cate_desc,null as created_at,null as cate_img_qu')
        ->orderBy('lexiang_meal_order.insert_time','desc')
        ->get();
        $shopname = MealShop::where('shop_id',$shopid)->value('shop_name');
        if(empty($orders->toArray())){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'本店没有待取订单',
                'data'=>[],
                'name'=>$shopname,
            ]);
        }
        $orderMeal = new MealOrder;
        foreach ($orders as $key => $value) {
            $o = MealOrder::where('order_id',$value->order_id)->first();
            $o->order_status = 1;
            if($o->users_id == $userid){
                MealHelpOrder::where('meal_order_id',$o->order_id)->update(['entrust'=>-2]);
                if($o->help_state == 2){
                    $userinfo = User::where('user_id',$o->help_user_id)->first();
                    $userinfo->account = $userinfo->account-1;
                    $userinfo->save();
                }
                $o->help_state = 3;
            }
            if($o->help_state==2){
                $o->help_state = 4;
            }
            $o->save();
            $orderMeal->scanWebSocket($value->order_id,$shopid,$value->order_sernum);
        }
        
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'取餐成功',
            'data'=>$orders,
            'name'=>$shopname,
        ]);
    }

    /**
     * 配送订单
     */
    public function deliveryOrder(Request $request)
    {
        $helporder = new MealHelpOrder;
        $orders = $helporder->leftJoin('lexiang_help_address','lexiang_help_address.user_id','=','lexiang_meal_help_order.users_id')
        ->where([
            ['lexiang_meal_help_order.status','=',1],
        ])
        ->selectRaw('lexiang_meal_help_order.*,lexiang_help_address.name,lexiang_help_address.tel,lexiang_help_address.address,null as help_user_name,null as help_to_username')
        ->orderBy('lexiang_meal_help_order.created_at','desc')
        ->paginate(15);

        return view('user.delivery',['orders'=>$orders,'request'=>$request]);
    }

    /**
     * 今日配送订单
     */
    public function deliveryOrderToday(Request $request)
    {
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayOver = strtotime(date('Y-m-d 23:59:59'));
        $helporder = new MealHelpOrder;
        $orders = $helporder->leftJoin('lexiang_help_address','lexiang_help_address.user_id','=','lexiang_meal_help_order.users_id')
        ->where([
            ['lexiang_meal_help_order.status','=',1],
        ])
        ->whereBetween('lexiang_meal_help_order.created_at',[$todayStart,$todayOver])
        ->selectRaw('lexiang_meal_help_order.*,lexiang_help_address.name,lexiang_help_address.tel,lexiang_help_address.address,null as help_user_name,null as help_to_username')
        ->orderBy('lexiang_meal_help_order.created_at','desc')
        ->paginate(15);

        return view('user.delivery',['orders'=>$orders,'request'=>$request]);
    }


    /**
     * 订单核销
     */
    public function scanCodeCheck(Request $request)
    {
        $nowtime = time();
        $company = new MealCompany;
        $cominfo = $company->where('token',$request->input('tcode'))->first();
        if(!$cominfo){
            return response()->json(['success'=>false,'code'=>'001','message'=>'tcode参数不正确']);
        }
        $randstr = $request->input('randstr');
        if($randstr < ($nowtime-(60*2))){
            return response()->json(['success'=>false,'code'=>'001','message'=>'请求已过期！']);
        }
        $mtkey = strtoupper($request->input('mdkey'));
        $k = strtoupper(md5($randstr.$cominfo->token));
        if($k != $mtkey){
            return response()->json(['success'=>false,'code'=>'001','message'=>'请求参数不正确！']);
        }
        // $shopid = $request->input('shop_id');
        $ordernumber = $request->input('order_number',false);
        if(empty($ordernumber)){
            return response()->json(['success'=>false,'code'=>'001','message'=>'请求参数不正确！']);
        }
        $ordernumber = explode('_', $ordernumber)[1];
        $orders = MealOrder::where('lexiang_meal_order.order_number',$ordernumber)
        ->where('lexiang_meal_shop.company_id',$cominfo->company_id)
        ->leftJoin('lexiang_meal_shop','lexiang_meal_shop.shop_id','=','lexiang_meal_order.shops_id')
        ->leftJoin('lexiang_user','lexiang_user.user_id','=','lexiang_meal_order.users_id')
        ->leftJoin('lexiang_meal_cate','lexiang_meal_cate.cate_id','=','lexiang_meal_order.cates_id')
        ->selectRaw('lexiang_meal_order.*,lexiang_user.nicename,lexiang_meal_cate.cate_name,lexiang_meal_shop.shop_name,lexiang_meal_shop.shop_address,lexiang_meal_cate.cate_imgs,lexiang_meal_cate.cate_desc,null as created_at,null as cate_img_qu')
        ->orderBy('lexiang_meal_order.insert_time','desc')
        ->get();
        if(empty($orders->toArray())){
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'此订单不属本窗口核销，请确认订单信息',
                'data'=>[]
            ]);
        }
        $orderMeal = new MealOrder;
        foreach ($orders as $key => $value) {
            $o = MealOrder::where('order_id',$value->order_id)->first();
            $o->order_status = 1;
            if(MealHelpOrder::where('meal_order_id',$o->order_id)->exists()){
                MealHelpOrder::where('meal_order_id',$o->order_id)->update(['entrust'=>-2]);
                if($o->help_state == 2){
                    $userinfo = User::where('user_id',$o->help_user_id)->first();
                    $userinfo->account = $userinfo->account-1;
                    $userinfo->save();
                }
                $o->help_state = 3;
            }
            if($o->help_state==2){
                $o->help_state = 4;
            }
            $o->save();
            $orderMeal->scanWebSocket($value->order_id,$value->shops_id,$value->order_sernum);
        }
        
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'取餐成功',
            'data'=>$orders
        ]);
    }

    public function test()
    {
        // 执行退款
        
        /*$wx = new \Wxpayandroid;
        $tui = $wx->refund(3,"159297227459167");
        dd($tui);*/
    }
}